package com.yonyou.sto.modules.ims.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonyou.sto.modules.ims.dto.ImsReturnInvoiceParam;
import com.yonyou.sto.modules.ims.model.ImsInvoice;
import com.yonyou.sto.modules.ims.model.ImsReturnInvoice;
import com.yonyou.sto.modules.ims.model.ImsReturnInvoiceItem;
import com.yonyou.sto.modules.ims.service.ImsReturnInvoiceItemService;
import com.yonyou.sto.modules.ims.service.ImsReturnInvoiceService;
import com.yonyou.sto.modules.ims.mapper.ImsReturnInvoiceMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
*
*/
@Service
public class ImsReturnInvoiceServiceImpl extends ServiceImpl<ImsReturnInvoiceMapper, ImsReturnInvoice>
implements ImsReturnInvoiceService{

    @Resource
    private ImsReturnInvoiceItemService returnSer;


    @Override
    public boolean add(List<ImsInvoice> imsInvoices) {
        imsInvoices.forEach(invoice->{
            ImsReturnInvoice re = new ImsReturnInvoice();
            BeanUtil.copyProperties(invoice, re);
            re.setId(null);
            re.setCreateTime(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
            re.setStatus(1);
            baseMapper.insert(re);
            returnSer.add(invoice.getId(), re.getId());
        });

        return true;
    }

    @Override
    public List<ImsReturnInvoiceParam> getListByBillSn(String billSn) {
        List<ImsReturnInvoice> rs =  baseMapper.getListByBillSn(billSn);
        List<ImsReturnInvoiceItem> ris = returnSer.getListByBillSn(billSn);
        List<ImsReturnInvoiceParam> rp = new ArrayList<>();
        rs.forEach(r -> {
            ImsReturnInvoiceParam p = new ImsReturnInvoiceParam();
            BeanUtil.copyProperties(r, p);
            p.setItems(ris.stream().filter(ri -> ri.getBillId().equals(r.getId())).collect(Collectors.toList()));
            p.setCreateTime(r.getCreateTime());
            rp.add(p);
        });
        return rp;
    }
}
